<template>
  <ms-dialog title="密码修改" ref="reDialog" width="500px" @ok="handleSaveForm" :dialogVisible="dialogVisible" @close="handleCloseReDialog">
    <el-form ref="formValid" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="原密码" prop="oldPwd">
        <el-input v-model="form.oldPwd" show-password type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="form.password" show-password type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input v-model="form.rePassword" show-password type="password" />
      </el-form-item>
    </el-form>
  </ms-dialog>
</template>

<script>
import MsDialog from '@/common/dialog'
import { mapActions } from 'vuex'
import { encrypt } from '@/utils/rsaEncrypt'
import { rePwd } from '@/api/sys/login'
export default {
  components: {
    MsDialog
  },
  data() {
    return {
      dialogVisible: false,
      form: {},
      rules: {
        oldPwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        rePassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions('user', ['logUserout']),
    handleSaveForm() {
      this.$refs['formValid'].validate((valid) => {
        if (valid) {
          const { oldPwd, password, rePassword } = this.form
          const saveForm = {
            oldPwd: encrypt(oldPwd),
            password: encrypt(password),
            rePassword: encrypt(rePassword)
          }
          rePwd(saveForm).then((res) => {
            this.$notify({
              message: res.obj,
              type: res.state ? 'success' : 'error'
            })
            // 成功后重新登陆
            if (res.state) {
              setTimeout(() => this.logUserout(), 3000)
            } else {
              this.$refs['reDialog'].disabled = false
            }
          })
        }
      })
      this.$refs['reDialog'].disabled = false
    },
    handleCloseReDialog() {
      this.dialogVisible = false
      this.form = {}
    }
  }
}
</script>
